package com.qf.timejob;

import com.alibaba.fastjson.JSONObject;
import com.qf.commons.SseEmitterUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * SseEmitter与 spring event
 */
// orderJob
public class SseEmitterJob {
    //判断是否有新通知
    private static boolean hasNewNotify = false;

    public static void setHasNewNotify(boolean hasNewNotify) {
        SseEmitterJob.hasNewNotify = hasNewNotify;
    }

    public void orderProcess() {

        if(SseEmitterUtils.seMap.size() > 0) {
            try{
                SseEmitterUtils.seMap.forEach((k, v) -> {
                    try {
                        Map<String, Object> map = new HashMap<>();
                        map.put("defalut","默认消息");
                        if (hasNewNotify){
                            map.put("title", "内部通知");
                            map.put("content", "有新的通知推送");
                            map.put("code",1);
                        }
                        String json = JSONObject.toJSONString(map);
                        v.send(SseEmitter.event().name("system_notify").data(json));
                        v.complete();
                    } catch (IllegalStateException ex) {  //如果出现异常，表示客户端关闭
                        SseEmitterUtils.seMap.remove(k);
//                    System.out.println(SseEmitterUtils.seMap.size());
                    } catch (IOException e) {

                    }
                });
                //当推送完信息后重置
                hasNewNotify = false;
            }catch (Exception ex){
                System.out.println("有一个连接断开");
            }

        }
    }
}
